package cn.wellwan.express;

import cn.wellwan.commons.WellwanBusinessException;
import cn.wellwan.config.WellwanHttpMessageConverter;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * Copyright (C),微动天下
 * FileName: SpringHttpClient
 * Author:   maokai
 * Date:     2018/12/19 13:21
 * Description: springhttp 工具
 */
@Component
@Log4j2
public class SpringHttpClient {

    private final RestTemplate rest = new RestTemplate();

    public static final String mediaType = "json";

    public String httpExcute(Map<String, Object> params, HttpMethod httpMethod, String url) {
        String result = "";
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        HttpEntity requestEntity = new HttpEntity(params, headers);
        ResponseEntity<String> entity = rest.exchange(url, httpMethod, requestEntity, String.class, new Object[0]);
        result = entity.getBody();
        HttpHeaders headers1 = entity.getHeaders();
        MediaType contentType = headers1.getContentType();
        String subtype = contentType.getSubtype();
        log.debug("SpringHttpClient返回的提示信息------>{}", result);
        if (mediaType.equals(subtype)) {
            log.info("SpringHttpClient返回的提示信息------>{}", result);
            throw new WellwanBusinessException(result);
        }
        return result;
    }

    public String httpExcute(Map<String, Object> params,  HttpHeaders headersMap, HttpMethod httpMethod, String url) {
        String result = "";
        HttpEntity requestEntity = new HttpEntity(params, headersMap);
        rest.getMessageConverters().add(new WellwanHttpMessageConverter());
        ResponseEntity<String> entity = rest.exchange(url, httpMethod, requestEntity, String.class, new Object[0]);
        result = entity.getBody();
        HttpHeaders headers1 = entity.getHeaders();
        MediaType contentType = headers1.getContentType();
        String subtype = contentType.getSubtype();
        log.debug("SpringHttpClient返回的提示信息------>{}", result);
        if (mediaType.equals(subtype)) {
            log.info("SpringHttpClient返回的提示信息------>{}", result);
            throw new WellwanBusinessException(result);
        }
        return result;
    }
}
